package com.itheima.service.impl;

import com.itheima.pojo.GoodInfo;
import com.itheima.pojo.PageResult;
import com.itheima.service.searchGoodsService;
import com.itheima.util.ElasticUtils;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class searchGoodsImpl implements searchGoodsService {

    @Autowired
    ElasticUtils elasticUtils;

    @Override
    public PageResult search(Integer page, Integer pageSize, String keyword, String price, String sort, boolean order) {
        //创建查询条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(QueryBuilders.matchQuery("title",keyword));

        //价格区间
        if (!StringUtils.isEmpty(price)){
            String[] priceAttr = price.split("-");
            RangeQueryBuilder rangePrice = QueryBuilders.rangeQuery("price");

            if (priceAttr!=null && priceAttr.length >0){
                rangePrice.gte(priceAttr[0]);
            }
            if (priceAttr!=null && priceAttr.length >1){
                rangePrice.lte(priceAttr[1]);
            }
            boolQueryBuilder.must(rangePrice);
        }

        searchSourceBuilder.query(boolQueryBuilder);

        //根据价格升序降序
        if (!StringUtils.isEmpty(sort)){
            searchSourceBuilder.sort(sort,order? SortOrder.ASC:SortOrder.DESC);
        }

        // 分页信息
        searchSourceBuilder.from(page);
        searchSourceBuilder.size(pageSize);


        //高亮字段显示
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        //三个参数
        highlightBuilder.field("title");
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");

        searchSourceBuilder.highlighter(highlightBuilder);

        PageResult<GoodInfo> searchResult = elasticUtils.search(searchSourceBuilder);

        // 计算有多少页
        Long total = searchResult.getTotal(); //总页数
        Long pages = total%pageSize == 0 ? total/pageSize : total/pageSize + 1;

        searchResult.setPages(pages);

        return searchResult;
    }


}
